<template>
  <el-drawer v-model="dialogVisible" :v-loading="loading" size="50%" @close="close">
    <template #header>
      <div style="font-size: 16px; font-weight: bold">{{ title }}</div>
    </template>
    <el-tree
      ref="menuTreeRef"
      :data="menuList"
      show-checkbox
      default-expand-all
      node-key="id"
      highlight-current
      check-on-click-node
      :props="defaultProps"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleClose(ruleFormRef)"
          >确定</el-button
        >
      </span>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElNotification, FormInstance } from 'element-plus'
import { menuorize, saveMenu } from '@/api/admin'
const loading = ref(false)
const saveLoading = ref(false)
const dialogVisible = ref(false)
const title = ref('权限')
const menuList = ref()
const defaultProps = {
  children: 'children',
  label: 'title',
}
const userId = ref()
const menuTreeRef = ref()

function close() {}

const show = (item = {}) => {
  userId.value = item.id
  title.value = item.title + '权限'
  dialogVisible.value = true
  gteAuthorize()
}

const gteAuthorize = () => {
  loading.value = true
  menuorize({ id: userId.value }).then((res) => {
    if (res.code == 200) {
      menuList.value = res.data
      let list = []
      menuList.value.forEach((item) => {
        if (item.children) {
          item.children.forEach((it) => {
            if (it.checked) {
              list.push(it.id)
            }
          })
        }
      })
      menuTreeRef.value.setCheckedKeys(list)
    }
    loading.value = false
  })
}

const handleClose = () => {
  let arr1 = menuTreeRef.value.getCheckedKeys()
  let arr2 = menuTreeRef.value.getHalfCheckedKeys()
  let node = arr1.concat(arr2)
  saveLoading.value = true
  saveMenu({
    id: userId.value,
    node: node,
  }).then((res) => {
    if (res.code == 200) {
      ElNotification({
        title: res.data,
        message: res.msg,
        type: 'success',
      })
      dialogVisible.value = false
    }
    saveLoading.value = false
  })
}

defineExpose({
  show,
})
</script>